<?php
/**
 * 微信用户
 *
 */

namespace dragon\User;

use dragon\Exceptions\UserException;
use think\Cache;
use think\Request;

class WechatUser
{
    const CACHE_PREFIX = 'wechat-user-openid=';

    // 获取账户信息
    public static function getByOpenid($openid)
    {
        static::clear($openid);
        return Cache::store('redis')->remember(static::cacheKey($openid), function () use ($openid) {
            return ThirdPartyUser::getByOpenid($openid);
        });
    } 
    
    // 添加 微信账号
    public static function registerThirdPartyUser($data, $userId = 0)
    {
        // 注册微信 用户
        $thirdPartyUser = new ThirdPartyUser([
            'user_id'       => $userId,
            'token'         => (string)$data['token'],
            'create_time'   => time(),
            'last_login_time' => time(),
            'last_login_ip'   => Request::instance()->ip(),
            'third_party'   => 'wechat',
            'nickname'      => (string)$data['nickname'],
            'avatar'        => (string)$data['headimgurl'],
            'openid'        => (string)$data['openid'],
            'sex'           => (string)$data['sex'],
        ]);

        $thirdPartyUser->save();

        if(!$userId) {
            // 注册用户
            $user = static::registerUser($thirdPartyUser);
        } else {
            $user = User::get($userId);
        }
        
        // 第三方用户 绑定
        static::relate($thirdPartyUser, $user);
        
        // 创建用户
        return $thirdPartyUser;
    }
    
    // 不存在时用户注册
    public static function registerUser(ThirdPartyUser $thirdPartyUser)
    {
        // 用户检测
        if($thirdPartyUser->user_id) throw new UserException('user_already_exists');

        $user = new User([
            'user_type'       => 3,
            'last_login_time' => time(),
            'create_time'     => time(),
            'user_nickname'   => $thirdPartyUser->nickname,
            'user_login'      => $thirdPartyUser->id.'_'.$thirdPartyUser->nickname,
            'avatar'          => $thirdPartyUser->avatar,
            'last_login_ip'   => Request::instance()->ip(),
        ]);
        
        $user->save();
        return $user;
    }
    
    // 用户ID 与 微信关联
    public static function relate(ThirdPartyUser $thirdPartyUser, User $user)
    {
        $thirdPartyUser->user_id = $user->id;
        $thirdPartyUser->save();
        $thirdPartyUser->user = $user;
        return $thirdPartyUser;
    }
    
    // 根据 openid 获取缓存键值
    public static function cacheKey($openid)
    {
        return static::CACHE_PREFIX.$openid;
    }

    // 清除 redis 缓存
    public static function clear($openid)
    {
        return Cache::store('redis')->rm(static::cacheKey($openid));
    }
}